package com.design.pattern.proxy.aop;

import com.design.pattern.proxy.RealSubject1;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

/**
 * @Projectname: design-pattern
 * @Filename: Cglib
 * @Author: FANSEA
 * @Date:2024/11/4 15:06
 */
public class Cglib {
    public static void main(String[] args) {
        RealSubject1 subject = new RealSubject1();
        // 创建cglib核心对象
        Enhancer enhancer = new Enhancer();
        // 设置父类
        enhancer.setSuperclass(subject.getClass());
        enhancer.setCallback(new MethodInterceptor(){
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("cglib代理开始");
                Object result = methodProxy.invoke(subject, objects);
                System.out.println("cglib代理结束");
                return result;
            }
        });
        RealSubject1 proxy = (RealSubject1) enhancer.create();
        proxy.request();
    }
}
